package org.sp1.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sp1.model.SpUser;
import org.sp1.service.UserService;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

public class LoginController extends AbstractCommandController {
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public LoginController() {
		setCommandClass(LoginCommand.class);
	}

	@Override
	protected ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		// TODO 自动生成方法存根
		LoginCommand loginCommand=(LoginCommand)command;
		
		boolean isUser=userService.hasMatchUser(loginCommand.getUserName(),loginCommand.getPassword());
		
		if(!isUser){
			return new ModelAndView("index","error","错的!!!!");
		}else{
			
			SpUser user=userService.findUserByUserName(loginCommand.getUserName());
			
			user.setLastIp(request.getLocalAddr());
			user.setLastVisit(new Date());
			
			userService.loginSuccess(user);
			request.getSession().setAttribute("user", user);
			
			return new ModelAndView("main");
		}
		

	}

}
